from flask import jsonify
from collections import Counter
from backend.utils import read_json_file


def count_list(data_list):
    genre_counter = Counter()
    for item in data_list:
        genre_group = item.get('genre', '')
        genres = genre_group.strip().split()  # 用空格分隔类型
        for genre in genres:
            if genre:  # 跳过空字符串
                genre_counter[genre] += 1
    return genre_counter


def get_movie_type_counts_api(app):
    @app.route('/api/movie/type/counts')
    def get_movie_type_counts():
        input_file = '../output.json'
        data_list = read_json_file(input_file)  # 是 list[dict]
        genre_counts = count_list(data_list)
        return jsonify(dict(genre_counts))  # 转换为字典返回 JSON
